//
//  MTHomeDouYinCell.swift
//  MT
//
//  Created by ooops on 2020/6/1.
//  Copyright © 2020 张强. All rights reserved.
//

import UIKit
import MTCategory
import Result
import RxSwift
import RxCocoa

protocol MTHomeDouYinNoVideoCellDelegate: NSObjectProtocol {
    /// 点赞
    func likeEvent(cell: MTHomeDouYinNoVideoCell, goodButton: GKLikeView, model: HomeListDetailModel?)
    /// 添加好友
    func addFriend(cell: MTHomeDouYinNoVideoCell, model: HomeListDetailModel?, sender: UIButton)
    /// 进入个人主页
    func entrancePersonal(cell: MTHomeDouYinNoVideoCell, model: HomeListDetailModel?)
    /// 屏蔽此人
    func black(userId: Int)
}

class MTHomeDouYinNoVideoCell: UICollectionViewCell {
    
    weak var delegate: MTHomeDouYinNoVideoCellDelegate?
    
    var playOrPauseBack: MTHomeDouYinCellPlayBack?
    
    var model1: HomeListDetailModel1? {
        didSet {
            coverImageView.mtSetImage(model1?.thumbnail_url, nil)
        }
    }
    
    private lazy var authProvider: MTProvider<DDCAuthAPI> = {
        let provider = MTProvider<DDCAuthAPI>()
        return provider
    }()
    
    /// 展示模型
    var model: HomeListDetailModel? {
        didSet {
            guard let model = model else { return }
            /// 封面图
            coverImageView.mtSetImage(model.imgs?.first?.href, nil)
            goodButton.setupLikeCount("\(model.likeCount)")
            goodButton.setupLikeState(model.selfLike != 0)
            
            userAvatarImageView.mtSetImage(model.headerUrl, nil)
            userNicknameLabel.text = "@ \(model.nickname ?? "")"
            /// 用户信息 Label
            userInfoLabel.text = "\(model.age ?? 0)岁  \(model.area ?? "")"
            //pauseIconButtonLeft.isHidden = !model.isContainVideo
            //addFriendButton.isHidden = model.isFriend
            if let un = model.userName, un == JMSGUser.myInfo().username || model.isFriend  {
                addFriendButton.isHidden = true
            } else {
                addFriendButton.isHidden = false
            }
            onlineStatusLabelLeft.isHidden = model.onlineStatus == 1
            onlineStatusLabelLeft.text = model.onlineStatusRemark
            coverImageView.bringSubviewToFront(goodButton)
        }
    }
    
    /// 同城隐藏所有信息
    func hiddenInfo(isHidden: Bool) {
        addFriendButton.isHidden = isHidden
        onlineStatusLabelLeft.isHidden = isHidden
        userInfoLabel.isHidden = isHidden
        userNicknameLabel.isHidden = isHidden
        userAvatarImageView.isHidden = isHidden
        goodButton.isHidden = isHidden
    }
        
    override func prepareForReuse() {
        //pauseIconButtonLeft.isSelected = false
        coverImageView.image = nil
        userInfoLabel.text = nil
    }
    
    class func reuseIdentity() -> String {
        return "MTHomeDouYinNoVideoCellID"
    }
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        makeConstraint()
    }
    
    lazy var coverImageView: UIImageView = {
        let imgView = UIImageView()
        imgView.contentMode = .scaleAspectFill
        imgView.isUserInteractionEnabled = true
        imgView.clipsToBounds = true
        imgView.tag = 100
        return imgView
    }()
    
    /// 视频暂停 / 开始按钮
//    lazy var pauseIconButtonLeft: UIButton = {
//        let btn = UIButton()
//        btn.setImage(UIImage(named: "icon_start"), for: .normal)
//        btn.setImage(UIImage(named: "icon_stop-1"), for: .selected)
//        btn.addTarget(self, action: #selector(MTHomeDouYinNoVideoCell.playVideo(sender:)), for: .touchUpInside)
//        return btn
//    }()
    
    lazy var userAvatarImageView: UIImageView = {
        let imageV = UIImageView()
        imageV.layer.cornerRadius = 22.auto()
        imageV.layer.masksToBounds = true
        imageV.contentMode = .scaleAspectFill
        imageV.backgroundColor = .red
        imageV.layer.borderColor = UIColor(hex: 0xffffff).cgColor
        imageV.layer.borderWidth = 1
        imageV.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer(target: self, action: #selector(MTHomeDouYinNoVideoCell.tapAvatar(tap:)))
        imageV.addGestureRecognizer(tap)
        return imageV
    }()
    
    /// 加好友按钮
    lazy var addFriendButton: UIButton = {
        let btn = UIButton()
        btn.setBackgroundImage(UIImage(named: "icon_addFriend"), for: .normal)
        btn.adjustsImageWhenHighlighted = false
        btn.addTarget(self, action: #selector(MTHomeDouYinNoVideoCell.didClickAddFriendButton(sender:)), for: .touchUpInside)
        return btn
    }()
    
    /// 是否在线
    lazy var onlineStatusLabelLeft: UILabel = {
        let label = UILabel()
        label.font = PingFangSCRegularFont(12)
        label.textColor = UIColor(hex: 0xffc000)
        label.backgroundColor = UIColor(hex:0x000000).withAlphaComponent(0.5)
        label.text = "15分钟前在线"
        label.textAlignment = .center
        return label
    }()
    
    /// 用户信息 Label
    lazy var userInfoLabel: UILabel = {
        let label = UILabel()
        label.font = PingFangSCMediumFont(12)
        label.textColor = .white
        label.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer(target: self, action: #selector(MTHomeDouYinNoVideoCell.tapAvatar(tap:)))
        label.addGestureRecognizer(tap)
        return label
    }()
    
    /// nicheng
    lazy var userNicknameLabel: UILabel = {
        let label = UILabel()
        label.font = PingFangSCMediumFont(16)
        label.textColor = .white
        label.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer(target: self, action: #selector(MTHomeDouYinNoVideoCell.tapAvatar(tap:)))
        label.addGestureRecognizer(tap)
        return label
    }()
    
    /// 点赞
    lazy var goodButton: GKLikeView = {
        let btn = GKLikeView(size: CGSize(width: 44.auto(), height: 44.auto()))
        let tap = UITapGestureRecognizer(target: self, action: #selector(MTHomeDouYinNoVideoCell.like))
        btn.addGestureRecognizer(tap)
        return btn
    }()
    
    /// 举报按钮
    lazy var reportButton: UIButton = {
        let btn = UIButton()
        btn.setTitle("举报", for: .normal)
        btn.titleLabel?.font = PingFangSCMediumFont(14)
        btn.setTitleColor(UIColor.theme.main, for: .normal)
        btn.layer.cornerRadius = 12
        btn.layer.borderWidth = 1
        btn.layer.borderColor = UIColor.theme.main.cgColor
        btn.layer.masksToBounds = true
        btn.adjustsImageWhenHighlighted = false
        btn.addTarget(self, action: #selector(homeDouYinNoVideoCell(didClickReportButtonButton:)), for: .touchUpInside)
        return btn
    }()
    
    /// 屏蔽按钮
    lazy var momentButton: UIButton = {
        let btn = UIButton()
        btn.setTitle("屏蔽", for: .normal)
        btn.titleLabel?.font = PingFangSCMediumFont(14)
        btn.setTitleColor(UIColor.theme.main, for: .normal)
        btn.layer.cornerRadius = 12
        btn.layer.borderWidth = 1
        btn.layer.borderColor = UIColor.theme.main.cgColor
        btn.layer.masksToBounds = true
        btn.adjustsImageWhenHighlighted = false
        btn.addTarget(self, action: #selector(homeDouYinNoVideoCell(didClickMomentButton:)), for: .touchUpInside)
        return btn
    }()
    
    @objc private func didClickAddFriendButton(sender: UIButton) {
        self.delegate?.addFriend(cell: self, model: model, sender: sender)
    }
    
    @objc private func like() {
        self.delegate?.likeEvent(cell: self, goodButton: goodButton, model: model)
    }
    
    @objc private func tapAvatar(tap: UITapGestureRecognizer) {
        self.delegate?.entrancePersonal(cell: self, model: model)
    }
    
    
    @objc private func playVideo(sender: UIButton) {
        self.playOrPauseBack?(sender)
    }
    
    /// 屏蔽信息流按钮
    @objc private func homeDouYinNoVideoCell(didClickMomentButton sender: UIButton) {
        // 取消按钮 index = 0
        let clickedHandler = { (sheetView: MTActionSheetView, index: Int) in
            if index == 0 {
                return
            }
            if index == 1 {
                let userId = self.model?.id ?? 0
                self.delegate?.black(userId: userId)
            }
        }
        
        let otherButtonTitles = ["屏蔽此人"]
        let actionSheet = MTActionSheetView(cancelButtonTitle: "取消",
                                          otherButtonTitles: otherButtonTitles,
                                          clickedHandler: clickedHandler)
        actionSheet.canTouchToDismiss = true
        actionSheet.show()
    }
    
    @objc private func homeDouYinNoVideoCell(didClickReportButtonButton sender: UIButton) {
        // 取消按钮 index = 0
        let clickedHandler = { (sheetView: MTActionSheetView, index: Int) in
            if index == 0 {
                return
            }
            self.report()
        }
        
        let otherButtonTitles = ["垃圾广告", "违法信息", "淫秽色情", "其他"]
        let actionSheet = MTActionSheetView(cancelButtonTitle: "取消",
                                          otherButtonTitles: otherButtonTitles,
                                          clickedHandler: clickedHandler)
        actionSheet.canTouchToDismiss = true
        actionSheet.show()
    }
    
    /// 举报用户的接口
    private func report() {
        
        if let un = self.model?.userName {
            MBProgressHUD_JChat.showLoading(UIApplication.mt_keyWindow, text: "正在上报, 请稍候")
            authProvider.originRequest(.report(username: un), callbackQueue: .main, progress: nil) { [weak self] (result, _) in
                switch result {
                case let .success(response):
                    if let datas = try? response.mapJSON() as? [String: Any], let code = datas["code"] as? Int, code == 200 {
                        MBProgressHUD_JChat.showLoading(UIApplication.mt_keyWindow, text: "感谢您的反馈, 系统将在24小时内处理")
                    } else {
                        MBProgressHUD_JChat.showLoading(UIApplication.mt_keyWindow, text: "举报失败, 请稍后重试")
                    }
                    DispatchQueue.main.after(2) {
                        MBProgressHUD_JChat.dismiss(UIApplication.mt_keyWindow)
                    }
                    break
                case .failure(_):
                    MBProgressHUD_JChat.showLoading(UIApplication.mt_keyWindow, text: "举报失败, 请稍后重试")
                    DispatchQueue.main.after(1) {
                        
                        DispatchQueue.main.after(2) {
                            MBProgressHUD_JChat.dismiss(UIApplication.mt_keyWindow)
                        }
                    }
                    break
                }
                
            }
        }
        
    }
    
    private func setupUI() {
        contentView.addSubview(coverImageView)
        //contentView.addSubview(pauseIconButtonLeft)
        contentView.addSubview(userAvatarImageView)
        //coverImageView.addSubview(sendGiftButton)
        contentView.addSubview(addFriendButton)
        contentView.addSubview(onlineStatusLabelLeft)
        contentView.addSubview(userInfoLabel)
        contentView.addSubview(userNicknameLabel)
        contentView.addSubview(goodButton)
//        coverImageView.addSubview(<#T##view: UIView##UIView#>)
    }
    
    private func makeConstraint() {
        coverImageView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        userAvatarImageView.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-9)
            make.bottom.equalToSuperview().offset(-221)
            make.size.equalTo(CGSize(width: 44.auto(), height: 44.auto()))
        }
        
        addFriendButton.snp.makeConstraints { (make) in
            make.centerX.equalTo(userAvatarImageView)
            make.centerY.equalTo(userAvatarImageView.snp.bottom)
            make.size.equalTo(CGSize(width: 25.auto(), height: 25.auto()))
        }
        
        goodButton.snp.makeConstraints { (make) in
            make.centerX.equalTo(userAvatarImageView)
            make.top.equalTo(userAvatarImageView.snp.bottom).offset(14)
            make.size.equalTo(CGSize(width: 44.auto(), height: 44.auto()))
        }
        
//        pauseIconButtonLeft.snp.makeConstraints { (make) in
//            make.center.equalToSuperview()
//            make.size.equalTo(CGSize(width: 50, height: 50))
//        }
        
        onlineStatusLabelLeft.snp.makeConstraints { (make) in
            make.left.equalTo(userInfoLabel)
            make.bottom.equalTo(userNicknameLabel.snp.top).offset(-5)
        }
        
        userInfoLabel.snp.makeConstraints { (make) in
            make.bottom.equalToSuperview().offset(-23)
            make.left.equalToSuperview().offset(10)
        }
        
        userNicknameLabel.snp.makeConstraints { (make) in
            make.left.equalTo(userInfoLabel)
            make.bottom.equalTo(userInfoLabel.snp.top).offset(-5)
        }
        
        if UserDefaults.AppValidate.isValidate.storedBool {

            contentView.addSubview(reportButton)
            contentView.addSubview(momentButton)

            reportButton.snp.makeConstraints { (make) in
                make.right.equalTo(userAvatarImageView)
                make.bottom.equalTo(userAvatarImageView.snp.top).offset(-9)
                make.width.equalTo(65)
                make.height.equalTo(24)
            }

            momentButton.snp.makeConstraints { (make) in
                make.right.equalTo(reportButton)
                make.bottom.equalTo(reportButton.snp.top).offset(-9)
                make.width.equalTo(65)
                make.height.equalTo(24)
            }

        }
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
}
